
#include <resource_cache/resource_cache.hpp>

resource_cache g_cache;

resource_cache::~resource_cache( )
{
	unload_images( );
	unload_buffers( );
}

sf::Image * resource_cache::load_image( std::string const & filename )
{
	sf::Image * out = get_image( filename );
	if ( out != 0 )
	{
		return out;
	}

	out = new sf::Image( );
	if ( out->LoadFromFile( filename ) )
	{
		m_images.insert( std::make_pair( filename, out ) );
		return out;
	}

	delete out;
	return 0;
}

sf::SoundBuffer * resource_cache::load_buffer( std::string const & filename )
{
	sf::SoundBuffer * out = get_buffer( filename );
	if ( out != 0 )
	{
		return out;
	}

	out = new sf::SoundBuffer( );
	if ( out->LoadFromFile( filename ) )
	{
		m_buffers.insert( std::make_pair( filename, out ) );
		return out;
	}

	delete out;
	return 0;
}

sf::Image * resource_cache::get_image( std::string const & keyname )
{
	images_t::const_iterator const iter = m_images.find( keyname );
	if( iter != m_images.end( ) )
	{
		return iter->second;
	}

	return nullptr;
}

sf::SoundBuffer * resource_cache::get_buffer( std::string const & keyname )
{
	buffers_t::const_iterator const iter = m_buffers.find( keyname );
	if( iter != m_buffers.end( ) )
	{
		return iter->second;
	}

	return nullptr;
}

void resource_cache::unload_images( )
{
	images_t::const_iterator const begin = m_images.begin( );
	images_t::const_iterator const end = m_images.end( );

	for (	images_t::const_iterator iter = begin;
			iter != end;
			++iter	)
	{
		delete iter->second;
	}

	m_images.clear( );
}
void resource_cache::unload_buffers( )
{
	buffers_t::const_iterator const begin = m_buffers.begin( );
	buffers_t::const_iterator const end = m_buffers.end( );

	for (	buffers_t::const_iterator iter = begin;
			iter != end;
			++iter	)
	{
		delete iter->second;
	}

	m_buffers.clear( );
}